<?php

namespace App\Listeners;

use App\Events\LeaveCar;
use App\Models\TaxiRelease;
use App\Models\TaxiReleaseInfo;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Contracts\Queue\ShouldQueue;
use Overtrue\Http\Exceptions\HttpException;


/**
 * 出租车业务处理
 *
 * Class AddFlowNumber
 * @package App\Listeners
 */
class  TaxiRecordUpdateSubscriber implements ShouldQueue
{

    /**
     * @param $events
     */
    public function subscribe($events)
    {
        $events->listen(
            'App\Events\LeaveCar',
            'App\Listeners\TaxiRecordUpdateSubscriber@add'
        );

        $events->listen(
            'App\Events\EnterCar',
            'App\Listeners\TaxiRecordUpdateSubscriber@update'
        );
    }

    /**
     * @param $event
     * @throws HttpException
     */
    public function add($event)
    {
        if (!$event->data->cardno) return;

        $release = TaxiRelease::where('uuid', $event->data->cardno)->first();
        if (!empty($release)) return;

        //删除旧授权
        $releaseInfo=TaxiReleaseInfo::where(['vpl_number' => $event->data->vpl_number])->get();

        if($releaseInfo->count()>0) {
            $releaseInfo->map(function ($item) use ($release){
                $http = new Client(['base_uri' => config('custom.car_now_auth_api_url')]);
                $releaseNo = TaxiRelease::where('uuid', $release->uuid)->first();
                //删除授权
                $res = $http->request('POST', 'auth_delete', ['form_params' =>
                    [
                        'park_code' => $releaseNo->in_park_code,
                        'cardno' => $releaseNo->uuid . md5($item->vpl_number)
                    ]]);
                if ($res->getStatusCode() != 200) {
                    throw new HttpException('delete_request_fail',$res);
                };

                $response = json_decode($res->getBody()->getContents());
                if (!$response || $response->code != 0) {
                    throw new HttpException('delete_fail',$res);
                }
                $item->delete();
            });

        }
//        sleep(1);
        //下发授权
        $http = new Client(['base_uri' => config('custom.car_now_auth_api_url')]);
        $cardNo = $release->uuid . md5((isset($event->data->vpl_number)?$event->data->vpl_number:''));
        $res = $http->request('POST', 'auth_group_add', ['form_params' =>
            [
                'park_code' => $release->in_park_code,
                'username' => $release->in_park_code,
                'cardno' => $cardNo,
                'type' => 5,
                'vpl_number' => \GuzzleHttp\json_encode([[$event->data->vpl_number, '']]),
                'validbtime' => Carbon::now()->getTimestamp(),
                'validetime' => Carbon::now()->addMinute(50)->getTimestamp(),
                'operator' => 'taxiDispatch',
                'email' => 'taxiDispatch@parkingwang.com',
                'share' => '0',
                'share_count' => 0,
                'serial_no' => $cardNo,
                'priority' => 2,
            ]]);
        if ($res->getStatusCode() != 200) {
            throw new HttpException('auth_request_fail',$res);
        };

        $json = $res->getBody()->getContents();
        \Log::error('update---- 出租车信息：'.$json);

        $response = json_decode($json);
        if (!$response || $response->code != 0) {
            throw new HttpException('auth_fail',$res);
        }


        $info = TaxiReleaseInfo::firstOrNew(
            [
                'vpl_number' => $event->data->vpl_number,
                'uuid' => $event->data->cardno
            ],
            [
                'out_record_id' => $event->data->record_id,
                'out_park_code' => $release->out_park_code,
                'in_park_code' => $release->in_park_code
            ]
        );

        $info->save();
    }

    /**
     * @param $event
     * @throws HttpException
     */
    public function update($event)
    {
        \Log::info('update 出租车信息：'.$event->data->vpl_number);
        $info = TaxiReleaseInfo::where([
            'vpl_number' => $event->data->vpl_number
        ])->orderBy('id','desc')->first();

        if (!$info) {
            return;
        }

        $info->in_record_id = $event->data->record_id;
        $info->in_time = Carbon::now();
        $info->save();

        $release = TaxiRelease::where('uuid', $info->uuid)->first();
        if (!$release) return;

        $http = new Client(['base_uri' => config('custom.car_now_auth_api_url')]);

        //删除授权
        $res = $http->request('POST', 'auth_delete', ['form_params' =>
            [
                'park_code' => $release->in_park_code,
                'cardno' => $release->uuid . md5($info->vpl_number)
            ]]);
        if ($res->getStatusCode() != 200) {
            throw new HttpException('delete_request_fail',$res);
        };

        $response = json_decode($res->getBody()->getContents());

        if (!$response || $response->code != 0) {
            throw new HttpException('delete_fail',$res);
        }

        $info->delete();
    }
}
